package com.laker.autotest.common.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;

import java.util.Properties;

public class EasyConfigLoader {

    private EasyConfigLoader() {
        // hide public constructor
    }

    public static EasyConfig loadEasyConfig() {
        YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
        yamlFactory.setResources(new ClassPathResource("application.yaml"));
        Properties properties = yamlFactory.getObject();

        if (properties != null) {
            StandardEnvironment environment = new StandardEnvironment();
            environment.getPropertySources().addFirst(new PropertiesPropertySource("yamlProperties", properties));
            Binder binder = Binder.get(environment);
            return binder.bind("easy", Bindable.of(EasyConfig.class)).orElseGet(EasyConfig::new);
        }
        return new EasyConfig();
    }
}
